// pages/goodsDetail/goodsDetail.js
const goodsService = require('../../service/goodsService.js')
const shopcart = require('../../service/shopcart.js')
const utils = require('../../utils/util.js');
// load promise 
require('../../utils/wx-pro.js');
var WxParse = require('../../wxParse/wxParse.js');
var timer = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsInfo: '',
    showNumBox: false,
    num: 1,
    showToast: false,
    toastMsg: '',
    groupList:[],
    goodlpricelist:{
      price:-1,
      ptprice:-1
    },
    page: {
      pageNo: 1,
      pageSize: 2
    },
    totalCount: 0,
    goodsId: '',
    shopId: '',
    allGoodsFilte: [],//商品规格数组
    goodspec:'',//被选中的商品规格
    goodPriceId:'',//规格分组的id
    goodprice:'',//显示的商品价格
    baseprice:'',//被选中的商品规格的价格
    isPtorDm:true,//true为单买,false为拼团,作为一个弹窗的标识
    // 购物车组件
    listpage:false,//购物车组件显示商品列表
    goodcart:false,//购物车的隐藏于显示
    allGoodslist:[],//购物车的商品列表
    pricecount:0,// 合计的价格
    listcount:0,//总计的数量
    cartnum:0//购物车的数量
  },
  //错误提示
  showToastFuc(msg) {
    this.setData({
      showToast: true,
      toastMsg: msg
    })
    setTimeout(() => {
      this.setData({
        showToast: false,
        toastMsg: ''
      })
    }, 2000)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options.goodId)
    var goodsId = options.goodId
    this.setData({
      goodsId: goodsId
    })
    if (options.shopId){
      var shopId = options.shopId
      this.setData({
        shopId: shopId
      })
    }else{
      var shopId = JSON.parse(wx.getStorageSync('selectShopInfo')).id
      this.setData({
        shopId: shopId
      })
    }
  },

  onShow: function(){
    this.getGoodsDetail({ goodsId: this.data.goodsId, shopId: this.data.shopId })
    this.getGroupList({ ptGoodsId: this.data.goodsId, shopId: this.data. shopId })
    this.getstoragelist()
    wx.showTabBar()
  },
  setallGoodsFilte(){
    var allGoodsFilte = []
    allGoodsFilte = [].concat(this.data.allGoodsFilte)
    this.setData({
      allGoodsFilte:[]
    })
    for (var i = 0; i < allGoodsFilte.length;i++){
      allGoodsFilte[i].checked=false
    }
    this.setData({
      allGoodsFilte: allGoodsFilte
    })
  },
  setTimer() {
    timer = setInterval(() => {
      var list = this.data.groupList
      for (var i = 0; i < list.length;i++){
        if (list[i].remain > 1000) {
          var remain = "groupList[" + i + "].remain"
          var remainFormat = "groupList[" + i + "].remainFormat"
          this.setData({
            [remain]: list[i].remain - 1000,
            [remainFormat]: this.secondToDate(list[i].remain / 1000)
          })
        }else{
          var remainFormat = "groupList[" + i + "].remainFormat"
          this.setData({
            [remainFormat]: ''
          })
        }
      }
    }, 1000)
  },
  secondToDate(result) {
    var h = Math.floor(result / 3600);
    var m = Math.floor((result / 60 % 60));
    var s = Math.floor((result % 60));
    if (h > 0) {
      return result = h + "小时" + m + "分钟" + s + "秒";
    } else {
      return result = m + "分钟" + s + "秒";
    }
  },
  clearTimer() {
    timer = clearInterval(timer)
  },

  getGoodsDetail(params){//商品详情
    goodsService.getGoodsDetail(params).then(data => {
      if (data.code == 200) {
        var list = data.response.xcxGoods
        list.param = JSON.parse(list.param)
        var xcxShopPriceLists = data.response.xcxShopPriceList
        var goodprice=[]
        for (var i = 0; i < xcxShopPriceLists.length;i++){
          var obj={}
          obj['count'] = xcxShopPriceLists[i].count
          obj['checked']=false
          obj['name'] = xcxShopPriceLists[i].count + xcxShopPriceLists[i].spec
          obj['price'] = xcxShopPriceLists[i].price
          obj['ptprice'] = xcxShopPriceLists[i].ptPrice
          obj['shopPriceId'] = xcxShopPriceLists[i].shopPriceId
          goodprice.push(obj)
        }
        if (xcxShopPriceLists.length>0){
          var price = xcxShopPriceLists[0].price
          var ptprice = xcxShopPriceLists[0].ptPrice
        }else{
          var price = list.price
          var ptprice = list.ptPrice
        }
        
        // console.log("ptprice", ptprice)
        this.setData({
          goodsInfo: list,
          allGoodsFilte: goodprice,
          goodlpricelist:{
            price:price,
            ptprice:ptprice,
          },
          baseprice: price
        })
        var detail = list.detail
        var that = this;
        WxParse.wxParse('detail', 'html', detail, that, 5);
      } else {
        this.showToastFuc(data.message)
      }
    })
      .catch((e) => {
        console.log(e)
      })
  },

  getGroupList(params){
    params.pageNo = 1
    params.pageSize = 2
    goodsService.listXcxOpenGroup(params).then(data => {
      if (data.code == 200) {
        var array = data.response.xcxOpenGroupList
        for (var i of array) {
          i.remain = i.endTime - data.timestamp
          i.remainFormat = ''
        }
        this.setData({
          groupList: array,
          totalCount: data.response.page.totalCount
        })
        this.clearTimer()
        this.setTimer()
      } else {
        this.showToastFuc(data.message)
      }
    })
      .catch((e) => {
        console.log(e)
      })
  },

  colseNumBox(){
    this.setData({
      showNumBox: false
    })
  },
  
  showNum(){//单独购买的打开弹窗
    if (this.data.goodsInfo.stockNum>0){
      this.setallGoodsFilte()
      this.setData({
        showNumBox: true,
        isPtorDm:true,
        num:1,
        goodspec:-1,
        goodprice: (parseFloat(this.data.goodlpricelist.price)).toFixed(2)
      })
      // console.log(this.data.allGoodsFilte)
    }else{
      this.showToastFuc("此商品已售罄")
    }
  },
  buyPt() {//拼团一键开团
    this.setallGoodsFilte()
    this.setData({
      showNumBox: true,
      isPtorDm: false,
      num: 1,
      goodspec:-1,
      goodprice: (parseFloat(this.data.goodlpricelist.ptprice)).toFixed(2)
    })
    // console.log(this.data.allGoodsFilte)
  },
  numJian(){//数量减少
    // console.log(this.data.goodprice , this.data.baseprice)
    if(this.data.num > 1){
      this.setData({
        num: this.data.num - 1,
        goodprice: (parseFloat(this.data.goodprice) - parseFloat(this.data.baseprice)).toFixed(2)
      })
    }
  },
  numJia() {//数量增加
    // console.log(this.data.goodprice, this.data.baseprice)
    this.setData({
      num: this.data.num + 1,
      goodprice: (parseFloat(this.data.goodprice) + parseFloat(this.data.baseprice)).toFixed(2)
    })
  },

  buyOne(){//弹出框的确认
  var _this=this
    if (this.data.goodspec == -1) {
      this.showToastFuc('请选择规格')
      return
    }
    if (this.data.isPtorDm) {//true为加入购物车,false为拼团,作为一个弹窗的标识
      var goodsInfo = this.data.goodsInfo
      //加入购物车
      var params = {
        goodsId: this.data.goodsInfo.goodsId,
        num:this.data.num, 
        shopId: this.data.shopId,
        count: this.data.goodPriceId
      }
      shopcart.saveshopcart(params).then(r=>{
        if(r.code==200){
          _this.showToastFuc('添加成功')
          _this.setData({
            showNumBox:false
          })
        }else{
          _this.showToastFuc(r.message)
        }
      })
      this.getstoragelist()

    }else{
      var goodsInfo = this.data.goodsInfo
      if (goodsInfo.stockNum > 0) {
        var goods = { num: 1, buyType: 2, goodspec: this.data.goodspec, goodprice: this.data.goodprice, goods: goodsInfo }
        wx.setStorageSync('orderGoods', JSON.stringify([goods]))
        this.setData({ goodspec: -1 })
        wx.setStorage({
          key: 'buytype',
          data: 2,
          success: function () {
            wx.navigateTo({
              url: '../orderConfirm/orderConfirm'
            })
          }
        })
      } else {
        this.showToastFuc("此商品已售罄")
      }
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      showNumBox: false
    })
  },
  serviceValChange(e) {//监听选择的规格,动态改变相应的class以及显示的价格
    // console.log(e)
    var allGoodsFilte = this.data.allGoodsFilte;
    var checkArr = e.detail.value;
    for (var i = 0; i < allGoodsFilte.length; i++) {
      if (allGoodsFilte[i].count == checkArr) {
        var goodPriceIds = allGoodsFilte[i].count
        allGoodsFilte[i].checked = true;
        if (this.data.isPtorDm) {//依照isPtorDm判断是单买还是拼团
          if (this.data.num>1){
            var gp = (parseFloat(allGoodsFilte[i].price) * this.data.num).toFixed(2)
            this.setData({
              goodprice: gp,
              baseprice: (parseFloat(allGoodsFilte[i].price)).toFixed(2)
            })
          }else{
            this.setData({
              goodprice: (parseFloat(allGoodsFilte[i].price)).toFixed(2),
              baseprice: (parseFloat(allGoodsFilte[i].price)).toFixed(2)
            })
          }
        }else{
          this.setData({
            goodprice: (parseFloat(allGoodsFilte[i].ptprice)).toFixed(2)
          })
        }
      } else {
        allGoodsFilte[i].checked = false;
      }
    }
    var goodspecs = parseInt(checkArr)

    this.setData({
      allGoodsFilte: allGoodsFilte,
      goodspec: goodspecs,
      goodPriceId: goodPriceIds
    })
  },
  lookMore(){
    wx.navigateTo({
      url: 'groupList/groupList?goodId=' + this.data.goodsInfo.goodsId + '&shopId=' + this.data.goodsInfo.shopId
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
   return{
     title: '【让我来微仓】' + this.data.goodsInfo.name,
     path: '/pages/goodsDetail/goodsDetail?goodId=' + this.data.goodsInfo.goodsId + '&shopId=' + this.data.goodsInfo.shopId
   }
  },
  toindex(){
    wx.switchTab({
      url:'../index/index'
    })
  },
  toshopcart(){
    wx.switchTab({
      url: '../shopcart/shopcart'
    })
  },
  //======================================================
  // 购物车组件方法
  //======================================================

  shoulistpage(){
    if (this.data.allGoodslist.length==0){
      return
    }
    this.setData({
      listpage: !this.data.listpage
    })
    this.getstoragelist()
  },
  // 加入购物车的时候向storage里提交数据++
  // 已选商品列表里显示{名称,价格,数量}++

  // #########获取购物车列表#########
  getstoragelist() {
    var _this=this
    var getlistarr=[]
    var params={
      shopId: this.data.shopId
    }
    shopcart.cartlist(params).then(r=>{
      if(r.code==200){
        if (r.response.shoppingCartList.length>0){
          _this.setData({
            cartnum: r.response.shoppingCartList.length
          })
        }
      }else{
        _this.showToastFuc(r.message)
      }
    })
  },
  // 购物车从storage里抽取数据
  // onshow的时候,触发函数,从storage里抽数据给allGoodslist用于显示,如果length==0,那么listpage为false

  // #########设置storage的ShopCartList的方法,传入参数为数组类型#########
  settostorage(arr) {

  },
  // 点击加入购物车的确认后,再次触发函数,从storage里抽取数据
  // 点击"去结算"后,触发跳转到订单确认页的方法

  //#########去结算#########
  settlement() {
    wx.setStorage({
      key: 'buytype',
      data: 1,
      success: function () {
        wx.navigateTo({
          url: '../orderConfirm/orderConfirm'
        })
      }
    })
  },
  //单个商品的数量增减
  //入参index
  //依照index改变storage里相应商品的值
  //然后刷新

  // #########增减数量的方法#########
  // changenum(e) {
  //   var _this=this
  //   var idx = e.currentTarget.dataset.index  // 标识符,第几个商品
  //   var maths = e.currentTarget.dataset.type // 类型,是添加还是减少
  //   var getlistarr=[]
  //   getlistarr = JSON.parse(wx.getStorageSync('ShopCartList'))// 获取列表
  //   if (maths=="add"){// 新增的时候直接+1
  //     getlistarr[idx].num = getlistarr[idx].num + 1
  //     getlistarr[idx].goodprice = parseFloat(getlistarr[idx].baseprice * getlistarr[idx].num).toFixed(2)
  //     this.computedcount()
  //   } else if (maths == "red"){
  //     // 减的时候需要判断,如果大于1,就减,else就从数组里去掉这个
  //     if (getlistarr[idx].num>1){
  //       getlistarr[idx].num = getlistarr[idx].num - 1
  //       getlistarr[idx].goodprice = parseFloat(getlistarr[idx].baseprice * getlistarr[idx].num).toFixed(2)
  //       //此处需要判断ShopCartList的长度,如果为0,那么隐藏
  //       if (getlistarr.length<=0){
  //         this.setData({
  //           listpage:false
  //         })
  //       }
  //       this.computedcount()
  //     }else{
  //       getlistarr.splice(idx,1)
  //       this.computedcount()
  //       if (getlistarr.length <= 0) {
  //         this.setData({
  //           listpage: false
  //         })
  //       }
  //     }
  //   }
  //   this.settostorage(getlistarr)
  //   // console.log(getlistarr)
  //   this.getstoragelist()
  // },
  // #########计算合计的数量和总价的方法,通过触发计算#########
  // 计算的同时判断购物车是否为空,为空的话,设置隐藏购物车
  computedcount() {
    var _this=this
    if (!JSON.parse(wx.getStorageSync('ShopCartList'))){
      return
    }
    var getlistarr=[]
    getlistarr = JSON.parse(wx.getStorageSync('ShopCartList'))
    if (getlistarr.length<=0){
      this.setData({
        goodcart:false
      })
    }else{
      this.setData({
        goodcart: true
      })
    }
    var pricecount=0 //总价
    var tt=0 //个数
    for (var i = 0; i < getlistarr.length; i++){
      pricecount += parseFloat(getlistarr[i].goodprice)
      tt++
    }
    this.setData({
      pricecount: pricecount.toFixed(2),
      listcount: tt
    })
  },
  // #########移除storage里ShopCartList字段的所有参数#########
  removeallgoodlist() {
    var _this=this
    wx.removeStorage({
      key: 'ShopCartList',
      success: function (res) {
        _this.setData({
          listpage:false,
          goodcart: false,//购物车的隐藏于显示
          allGoodslist: [],//购物车的商品列表
          pricecount: 0,// 合计的价格
          listcount: 0,//总计的数量
        })
      }
    })
  }
})